/*
* Licensed under the MIT License
* 
* Copyright (c) 2010 Kay Kreuning
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* 
* http://code.google.com/p/as3hyvesapi
*/
package nl.hyves.api
{
	import flash.net.URLRequest;
	
	import nl.hyves.api.delegates.APICallDelegate;
	import nl.hyves.api.delegates.IAPICallDelegate;
	import nl.hyves.api.errors.HyvesError;
	import nl.hyves.api.sessions.Accesstoken;
	import nl.hyves.api.sessions.ISession;
	import nl.hyves.api.utils.AuthUtil;
	
	import org.osflash.signals.ISignal;
	import org.osflash.signals.Signal;
	
	public class HyvesService
	{
		private const API_ENDPOINT:String = "http://data.hyves-api.nl/";
		
		private var consumerKey:String;
		private var consumerSecret:String;
		private var session:ISession;
		private var accesstoken:Accesstoken;
		
		private var _connectedSignal:Signal;
		private var _disconnectedSignal:Signal;
		private var _errorSignal:Signal;
		
		public function get connectedHandler():ISignal
		{
			return _connectedSignal ||= new Signal();
		}
		
		public function get disconnectedHandler():ISignal
		{
			return _disconnectedSignal ||= new Signal(HyvesError);
		}
		
		public function get errorHandler():ISignal
		{
			return _errorSignal ||= new Signal(HyvesError);
		}
		
		public function get isConnected():Boolean
		{
			return (accesstoken && accesstoken.userId && accesstoken.methods && accesstoken.expireDate);
		}
		
		public function get userId():String
		{
			return accesstoken ? accesstoken.userId : null;
		}
		
		public function get methods():Array
		{
			return accesstoken ? accesstoken.methods : null;
		}
		
		public function get expireDate():Date
		{
			return accesstoken ? accesstoken.expireDate : null;
		}
		
		public function HyvesService(consumerKey:String, consumerSecret:String, session:ISession = null)
		{
			this.consumerKey = consumerKey;
			this.consumerSecret = consumerSecret;
			
			if (session)
				connect(session);
		}
		
		public function call(method:String, parameters:Object = null):IAPICallDelegate
		{
			parameters ||= new Object();
			
			parameters["ha_method"] = method;
			parameters["ha_version"] = "2.0";
			parameters["ha_format"] = "xml";
			parameters["ha_fancylayout"] = "false";
			parameters["ha_responsecode_always_200"] = "true";
			
			var request:URLRequest = AuthUtil.createRequest(parameters, API_ENDPOINT, consumerKey, consumerSecret, accesstoken);
			
			var delegate:IAPICallDelegate =  new APICallDelegate(request);
			delegate.errorHandler.addOnce(handleError);
			
			return delegate;
		}
		
		public function connect(session:ISession):void
		{
			this.session = session;
			accesstoken = null;
			
			session.accesstokenDispatcher.add(onAccesstoken);
			session.connect(call);
		}
		
		private function onAccesstoken(accesstoken:Accesstoken):void
		{
			this.accesstoken = accesstoken;
			
			if (isConnected)
				_connectedSignal.dispatch();
		}
		
		private function handleError(error:HyvesError):void
		{
			switch (error.code)
			{
				case 17:	// OAuth token is invalid
				case 25:	// The supplied token has expired
				case 27:	// A requesttoken can only be used with the method auth.accesstoken (user declined authorization)
				case 31:	// The requesttoken used to obtain an accesstoken was not authorized
				case 32:	// The requesttoken used to obtain an accesstoken was declined by the user
				case 101:	// No access, (other)OAuth token required (user declined authorization)
					accesstoken = null;
					_disconnectedSignal.dispatch(error);
					break;
				default:
					_errorSignal.dispatch(error);
					break;
			}
		}
	}
}